package com.co0964.fetcher;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

import com.co0964.Main;
import com.co0964.bean.Category;
import com.co0964.bean.Product;

public class ProductFetcher {
	
	private HttpClient client = new HttpClient();
	private int categoryId;
	private List<Product> list = new ArrayList<Product>();
	private int totalPage = 1;
	private int currPage = 1;
	
	public ProductFetcher(int categoryId){
		this.categoryId = categoryId;
	}
	
	public List<Product> fetch(){
		fetchList();
		fetchDetail();
		return list;
	}
	
	private void fetchList(){
		PostMethod getMethod = null;
		for(int i=0; i<totalPage; i++){
			try{
				getMethod = new PostMethod("http://0964.co.kr/front/php/category.php?cate_no=" + categoryId + "&page=" + (i+1));
				getMethod.addRequestHeader("Cookie", Main.COOKIE);
				client.executeMethod(getMethod);
				String result = getMethod.getResponseBodyAsString();
				parseList(result);
			}catch (Exception e) {
				e.printStackTrace();
			}finally{
				getMethod.releaseConnection();
			}
		}
	}
	
	private void parseList(String content){
		Matcher matcher = Pattern.compile("/front/php/category.php\\?cate_no=\\d+?&page=(\\d+?)").matcher(content);
		while(matcher.find()){
			int temp = Integer.parseInt(matcher.group(1));
			if(temp > totalPage){
				totalPage = temp;
			}
		}
		
		matcher = Pattern.compile("width=\"760\"([\\s\\S]*?)body end").matcher(content);
		matcher.find();
		content = matcher.group(1);
		
		matcher = Pattern.compile("<img src=\"http://0964.co.kr/web/product/tiny/sw0962_(\\d+?).jpg\" style=\"border:1 solid #D7D7D7\">").matcher(content);
		while(matcher.find()){
			Product product = new Product();
			product.setPid(Integer.parseInt(matcher.group(1)));
			product.setImg("http://0964.co.kr/web/product/tiny/sw0962_" + product.getPid() + ".jpg");
			product.setCid(categoryId);
			list.add(product);
			System.out.println(product.getPid());
		}
			
	}
	
	
	private void fetchDetail(){
		PostMethod getMethod = null;
		for(int i=0; i<list.size(); i++){
			try{
				System.out.print(i + " / " + list.size());
				Product product = list.get(i);
				getMethod = new PostMethod("http://0964.co.kr/front/php/product.php?product_no=" + product.getPid());
				getMethod.addRequestHeader("Cookie", Main.COOKIE);
				client.executeMethod(getMethod);
				String result = getMethod.getResponseBodyAsString();
				parseDetail(result, product);
			}catch (Exception e) {
				e.printStackTrace();
			}finally{
				getMethod.releaseConnection();
			}
		}
	}
	
	
	private void parseDetail(String content, Product product){
		Matcher matcher = Pattern.compile("<input type=\"hidden\" name=\"product_name\" value=\"(.*?)\">").matcher(content);
		matcher.find();
		product.setPname(matcher.group(1));
		
		try{
			matcher = Pattern.compile("<span id=main_price>(.*?)</span>").matcher(content);
			matcher.find();
			product.setPrice(Integer.parseInt(matcher.group(1).replaceAll(",|원", "")));
		}catch (Exception e) {}
		
		try{
			//matcher = Pattern.compile("<IMG src=\"(.*?)\">").matcher(content);
//			matcher = Pattern.compile("src=\"(((http://0964)|(http://sw0962)|(\\/web)).*?all_img.*?)\"").matcher(content);
			StringBuffer sb = new StringBuffer();
			matcher = Pattern.compile("src=\"(((http://0964)|(http://sw0962)|(/web)).*?all_img.*?)\"").matcher(content);
			while(matcher.find()){
				String src = matcher.group(1);
				if(sb.length() > 0){
					sb.append("\n");
				}
				if(!src.startsWith("http")){
					src = "http://0964.co.kr" + src;
				}
				sb.append(src);
			}
			product.setWr1(sb.toString());
		}catch (Exception e) {}
		System.out.println(product);
	}
	
	public void close(){
		try{
			client.getHttpConnectionManager().closeIdleConnections(0);
		}catch (Exception e) {
		}
	}

}
